<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <link rel="icon" href="./favicon.png" />
  <meta name="viewport"
    content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
  <meta http-equiv="Cache-control" content="no-cache">
  <meta http-equiv="Cache" content="no-cache">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black" />
  <title>汇文模拟答题</title>
</head>

<body>
  <div id="app"></div>
  <script type="module" src="/src/main.js"></script>
  <script>
    // check token
    var tokenInfo = localStorage.getItem('tokenInfo')
    console.log("checkToken tokenInfo:" + tokenInfo)
    if (tokenInfo) {
      var params = JSON.parse(tokenInfo)
      const queryString = Object.keys(params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&')
      const xhr = new XMLHttpRequest()
      xhr.open('POST', '/checkToken')
      xhr.onload = async function () {
        var res = JSON.parse(xhr.response);
        console.log(res)
        var success = false
        if (res.code === 200) {
          console.log("index checkToken 验证token成功")
          if (res.token) {
            success = true
            var tokenInfo = {
              username: params.username,
              deadline: res.deadline,
              token: res.token
            }
            localStorage.setItem('tokenInfo', JSON.stringify(tokenInfo))
          }
        }
        if (success) {
          console.log("checkToken success")
        } else {
          console.log("index checkToken fail, go login")
          window.location.href = "/login.html"
        }
      }
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
      xhr.send(queryString);
    } else {
      console.log("no token, go login")
      window.location.href = "/login.html"
    }
  </script>
</body>

</html>